package com.ly.algorithm.offerpointer;

/**
 * @Classname Offer04
 * @Description
 *
 * 剑指 Offer 04. 二维数组中的查找
 * 在一个 n * m 的二维数组中，每一行都按照从左到右递增的顺序排序，每一列都按照从上到下递增的顺序排序。请完成一个高效的函数，输入这样的一个二维数组和一个整数，判断数组中是否含有该整数。
 *
 *
 *
 * 示例:
 *
 * 现有矩阵 matrix 如下：
 *
 * [
 *   [1,   4,  7, 11, 15],
 *   [2,   5,  8, 12, 19],
 *   [3,   6,  9, 16, 22],
 *   [10, 13, 14, 17, 24],
 *   [18, 21, 23, 26, 30]
 * ]
 *
 * 给定 target = 5，返回 true。
 *
 * 给定 target = 20，返回 false。
 *
 * @Date 2020/12/30 19:11
 * @Author 冷心影翼
 */
public class Offer04 {

    public static void main(String[] args) {
        Solution04 solution04 = new Solution04();
        int[][] matrix = new int[][] {
            {1,   4,  7, 11, 15},
            {2,   5,  8, 12, 19},
            {3,   6,  9, 16, 22},
            {10, 13, 14, 17, 24},
            {18, 21, 23, 26, 30}
        };
        System.out.println(solution04.findNumberIn2DArray(matrix, 20));
        System.out.println(solution04.findNumberIn2DArrayBestway(matrix, 5));
    }

}

class Solution04 {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        for (int i = 0; i < matrix.length; i++) {
            if(binarySearch(matrix[i],target)) {
                return true;
            }
        }
        return false;
    }

    public boolean findNumberIn2DArrayBestway(int[][] matrix, int target) {
        int n = matrix.length;
        if(n==0)
            return false;
        int m = matrix[0].length;
        int i = 0;
        int j = m-1;
        while (i<n && j>=0) {
            if(matrix[i][j] == target) {
                return true;
            }else if(matrix[i][j]<target) {
                i++;
            }else {
                j--;
            }
        }
        return false;
    }

    private boolean binarySearch(int[] arr,int target) {
        int l = 0;
        int r = arr.length-1;
        while (l<=r) {
            int mid = (l+r)/2;
            if(arr[mid] == target) {
                return true;
            }else if(arr[mid]<target) {
                l = mid+1;
            }else {
                r = mid-1;
            }
        }
        return false;
    }
}
